package org.example.test;

import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class test10 {
    public static void main(String[] args) throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.print("请输⼊要扫描的根⽬录（绝对路径 OR 相对路径): ");
        String rootDirPath = scanner.next();
        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()) {
            System.out.println("您输⼊的根⽬录不存在或者不是⽬录，退出");
            return;
        }
        System.out.print("请输⼊要找出的⽂件名中的字符: ");
        String token=scanner.next();
        List<File> result=new ArrayList<>();
        // 因为⽂件系统是树形结构，所以我们使⽤深度优先遍历（递归）完成遍历
        scanDirWithContent(rootDir, token, result);
        System.out.println("找到的文件有："+result);
        for (File file : result){
            System.out.println(file.getCanonicalPath());
        }
    }

    public static void scanDirWithContent(File dir, String token, List<File> result) throws FileNotFoundException {
        File [] files=dir.listFiles();
        if (files ==null || files.length==0){
            return;
        }
        for (File file : files){
            if (file.isDirectory()){
                scanDirWithContent(file, token, result);
            }else {
                if (isContentContains(file, token)){
                    result.add(file.getAbsoluteFile());
                }
            }
        }
    }
    public static boolean isContentContains(File file, String token) throws FileNotFoundException {
        StringBuilder sb=new StringBuilder();
        InputStream is=new FileInputStream(file);
        Scanner scanner=new Scanner(is,"UTF-8");
        while (scanner.hasNext()){
            sb.append(scanner.next());
            sb.append("\r\n");
        }
        return sb.indexOf(token) !=-1;
    }
}
